<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Overtrue\Wechat\Server;
use Overtrue\Wechat\User as WxUser;
use Overtrue\Wechat\QRCode;
use App\http\models\UserModel;
use Overtrue\Wechat\Menu;
use Overtrue\Wechat\MenuItem;
use Overtrue\Wechat\Notice;
use PhpParser\Node\Stmt\DeclareDeclare;

class WxController extends Controller
{

/*   public function __construct()
    {
        $this->middleware('verify', ['except' => 'index']);
    }*/

    //
    public function index() {

        // $encodingAESKey 可以为空
        $server = new Server( env('WX_ID') , env('WX_TK') );
        $server->on('event' , 'subscribe' , [$this , 'guanzhu']);
        $server->on('event' , 'unsubscribe' , [$this , 'qxgz']);

        return $server->serve();
    }

    public function guanzhu ($event) {
        $openid= $event->FromUserName;

        $wxuser = new WxUser(env('WX_ID'),env('WX_SEC'));
        $wu = $wxuser->get($openid);
        $data=array(
            'openid'=>$openid,
            'nickname' => $wu->nickname,
            'create_time' => time(),
            'province' => $wu->province,
            'city' => $wu->city,
            'sex' => $wu->sex,
            'headimgurl' => $wu->headimgurl,
            'status' => 1,
            'is_tixing'=>0
        );

        $user_info=UserModel::where('openid',$openid)->first();
        if(empty($user_info)){
            UserModel::create($data);
        }else{
            UserModel::where('openid' , $openid)->update($data);
        }
         $msg = '欢迎你,' . $openid;
         return    $msg ;
    }
    public function createmenu(){

        $appId  = env('WX_ID');
        $secret = env('WX_SEC');
        $menuService = new Menu($appId, $secret);
        $menus = array(
            new MenuItem("首页", 'view', 'http://'.$_SERVER['HTTP_HOST'].'/home/show'),
            new MenuItem("日行一善", 'view', 'http://'.$_SERVER['HTTP_HOST'].'/home/xingshan'),
            new MenuItem("我的善木", 'view', 'http://'.$_SERVER['HTTP_HOST'].'/home/selfshan'),
        );

        try {
            $menuService->set($menus);// 请求微信服务器
            echo '设置成功！';
        } catch (\Exception $e) {
            echo '设置失败：' . $e->getMessage();
        }
    }

    public function qxgz($event) {
        $openid = $event->FromUserName;
        $user = UserModel::where('openid' , $openid)->first();
        if($user) {
            UserModel::where('openid' , $openid)->update(['status'=>0]);
        }
    }

    public function qr($uid) {
        // 开始生成场景二维码
        $qrcode = new QRCode(env('WX_ID') , env('WX_SEC'));
        $result = $qrcode->forever( $uid );
        $ticket = $result->ticket;

        // 下载二维码
        $qr = public_path() . $this->mkd() . '/' . 'qr_' . $uid . '.jpg' ;
        $qrcode->download($ticket,  $qr);
    }

    protected function mkd() {
        $path = date('/Y/md');
        if( !is_dir ( public_path() . $path ) ) {
            mkdir(public_path() . $path , 0777 ,true);
        }

        return $path;
    }
    public function get_user_info(){
        $openid='od6Lns-IoN0JbZE-8i3Ebg6kACpU';
        //$openid='owBAVv1AVZHxZZYXTkfagbYaaa--Jqs';
        $wxuser = new WxUser(env('WX_ID'),env('WX_SEC'));
        $wu = $wxuser->get($openid);
        //dd($wu);
       $data=array(
            'openid'=>$openid,
            'nickname' => $wu->nickname,
            'create_time' => time(),
            'province' => $wu->province,
            'city' => $wu->city,
            'sex' => $wu->sex,
            'headimgurl' => $wu->headimgurl,
            'status' => 1,
            'is_tixing'=>0
        );

        $user_info=UserModel::where('openid',$openid)->first();
        if(empty($user_info)){
            UserModel::create($data);
        }else{
            UserModel::where('openid' , $openid)->update($data);
        }
        $msg = '欢迎你,' .  $openid;
        dd($msg);
    }


    public function template_message(){
        $appId  = env('WX_ID');
        $secret = env('WX_SEC');
        $notice = new Notice($appId, $secret);
        $userId = 'od6Lns-IoN0JbZE-8i3Ebg6kACpU';
        $templateId = '0UdhBr3iqd04_a8zIwIRy9C_qSTS5j82HioYW8i7Rvc';
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/home/xingshan';
        $color = '#FF0000';
        $data = array(
            "title"    => "主人今天行善了吗，这样小木才能快速成长哦！！",
            "headinfo" => "巧克力",
            "program" => "39.8元",
            "result" => "2014年9月16日",
            "remark"   => "欢迎再次购买！",
        );
        $user= UserModel::where('is_tixing',1)->get()->toArray();
        foreach ( $user as $key => $value ){
            echo $value['openid'] ; echo '<br/>';
            $messageId = $notice->to($value['openid'])->color('#ff0000')->url($url)->withTemplateId($templateId)->send();
            //$messageId = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
        }
        dd( $user);
        dd('---------------');


    }


}

//  回调函数的调用格式
// 匿名函数
// 函数名 'time'
// 对方的方法 [对象 , 方法名]
// 静态方法 '类名::方法名'